package com.my.netty.optimize.allocator;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AllocatorServer {

    public static void main(String[] args) {
        ChannelConfig config = null;
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(new NioEventLoopGroup());
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            /*
                               默认alloc()分配的是PooledUnsafeDirectByteBuf，可以通过参数配置 池化/非池化；直接内存/堆内存
                                可通过系统变量指定默认分配器类型
                                -Dio.netty.allocator.type=pooled|unpooled
                                -Dio.netty.noPreferDirect=true|false
                                源码位置：io.netty.buffer.ByteBufUtil
                             */
                            ByteBuf buf = ctx.alloc().buffer();
                            log.info("alloc buf: {} msg: {}", buf, msg);
                        }
                    });
                }
            });
            serverBootstrap.bind(8080).sync();
            log.info("服务端已启动...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
